package org.ala.tcp_feign_client.handler.biz;

import java.util.function.Consumer;

import org.ala.tcp_feign_client.context.TcpFeignClientContext;
import org.ala.tcp_feign_common.config.AttrbuteKeyNamespace;
import org.ala.tcp_feign_common.enums.TcpFeignMessageTypeEnums;
import org.ala.tcp_feign_common.handler.IByteMessageAction;
import org.ala.tcp_feign_common.logs.LoggerFactory;
import org.ala.tcp_feign_common.msg.biz_resp.BizRespACKByteMessage;
import org.ala.tcp_feign_common.msg.biz_resp.BizRespByteMessage;
import org.slf4j.Logger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;


/**
 * 返回值消息action
 *
 * @author 骆毅(ala)
 * @date 2024年4月22日
 */
public class BizRespByteMessageAction implements IByteMessageAction<BizRespByteMessage> {
	
	
	static Logger log = LoggerFactory.getLogger("tcp-feign", "client");
	

	@Override
	public TcpFeignMessageTypeEnums type() {
		return TcpFeignMessageTypeEnums.BIZ_RESP;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void action(ChannelHandlerContext ctx, BizRespByteMessage msg) {
		//	先给回执
		ctx.channel().writeAndFlush(BizRespACKByteMessage.build(msg.getMsgId()));
		
		//	如果回调不为空，执行回调
		//	这里给线程池的意义：避免占用worker线程
		//	这里给回调的意义：每个client的 msgId <=> Future 映射 单独拆开，减少segument锁冲突
		Consumer<BizRespByteMessage> consumer = (Consumer<BizRespByteMessage>) ctx.channel().attr(AttributeKey.valueOf(AttrbuteKeyNamespace.BIZ_RESP_CALLBACK)).get();
		if (consumer != null) {
			try {
				TcpFeignClientContext.instance().getClientBizRespThreadPool().execute(() -> {
					consumer.accept(msg);
				});
			} catch (Exception e) {
				log.warn("[BizRespByteMessageAction action] 执行resp回调失败 msg:" + msg.getMsgId());
			}
		}
	}

}
